# plugs/convert.py
#
#

""" convert data """

__copyright__ = 'this file is in the public domain'
__thnx__ = 'bsod'

from gozerbot.commands import cmnds
from gozerbot.examples import examples
from gozerbot.plughelp import plughelp
import sys

plughelp.add('convert', 'convert data')

# converter functions 

def gallontoliter(num):
    return 3.7854118 * num

def litertogallon(num):
    return 1/3.7854118 * num
    
def metertofeet(num):
    return 3.2808399 * num

def feettometer(num):
    return 1/3.2808399 * num

def kmtomile(num):
    return 1/1.609344 * num

def miletokm(num):
    return 1.609344 * num

def celciustofahrenheit(num):
    return 1.8 * num + 32.0

def fahrenheittocelcius(num):
    return 0.5555555 * num + -17.7777777

def kelvintocelcius(num):
    return num - 273.0

def celciustokelvin(num):
    return num + 273.0

def fahrenheittokelvin(num):
    return 0.5555 * num + -17.77777777 + 273.000

def kelvintofahrenheit(num):
    return 1.8 * (num + 32.0) - 273.0

def inchtocm(num):
    return  2.540 * num

def cmtoinch(num):
    return 1/ 2.540 * num

def kgtolb(num):
    return 2.205 * num

def lbtokg(num):
    return 1/2.205 * num

def kgtooz(num):
    return 35.273 * num

def oztokg(num):
    return 1/35.273 * num

def oztolb(num):
    return 1/16 * num

def lbtooz(num):
    return 16 * num

def eurotogulden(num):
    return num * 2.20371

def guldentoeuro(num):
    return num * 1/2.20371

def handle_convert(bot, ievent):
    """ convert <nuw> <unit> to <unit> .. convert data """
    try:
        num = float(ievent.args[0])
        from_unit = ievent.args[1]
        if ievent.args[2] != 'to':
            raise()
        to_unit = ievent.args[3]
    except:
        ievent.reply('convert <num> <unit> to <unit>')
        return
    try:
        func = getattr(sys.modules['plugs.convert'], from_unit+'to'+to_unit)
        result = func(num)
    except (KeyError, AttributeError):
        ievent.reply("sorry can't convert from %s to %s" % (from_unit, \
to_unit))
        return
    except Exception, ex:
        ievent.reply('ERROR: %s' % str(ex))
        return
    ievent.reply('%s %s ==> %s %s' % (num, from_unit, result, to_unit))

cmnds.add('convert', handle_convert, 'USER')
examples.add('convert','convert <num> <unit> to <unit>', \
'convert 100 fahrenheit to celsius')

def handle_convertlist(bot, ievent):
    """ convert-list .. show al available converter functions """
    resultstr = ""
    for i in dir(sys.modules['plugs.convert']):
        if i.startswith('__'):
            continue
        if i in ('cmnds', 'examples', 'sys', 'plughelp'):
            continue
        resultstr += "%s " % i
    ievent.reply(resultstr)

cmnds.add('convert-list', handle_convertlist, 'USER')
examples.add('convert-list', 'list possible convertions', 'convert-list')
